import logging
from flask import request, jsonify
from user import userservice
from task import checker_task

logger = logging.getLogger(__name__)

def init_compliance_routes(app):
    """
    初始化合规检查相关路由
    """
    
    @app.route('/check', methods=['POST'])
    def check_product():
        source = request.args.get('source')
        source_id = request.args.get('source_id')
        user_id = userservice.get_user_by_source_id(source_id, source)
        if user_id is None:
            return jsonify({
                'error': '请先登录',
                'message': '请先登录, 联系管理员'
            }), 400

        data = request.get_json()
        logger.info(f"收到合规检查请求: {data}")
        if not data or 'product_name' not in data:
            return jsonify({
                'error': '请提供商品名称',
                'example': {
                    'product_name': '不锈钢保温杯'
                }
            }), 400

        product_name = data['product_name']
        pics = data['pics']
        
        try:
            response = checker_task.process_sync_task(user_id, product_name, pics)
            if response == '-10010001':
                return jsonify({
                    'error': '10010001',
                    'message': '可用次数不足'
                }), 200
            return jsonify(response)
        except Exception as e:
            return jsonify({
                'error': '10010000',
                'message': str(e)
            }), 500 


    @app.route('/records', methods=['GET'])
    def get_user_records():
        source = request.args.get('source')
        source_id = request.args.get('source_id')
        user_id = userservice.get_user_by_source_id(source_id, source)
        if user_id is None:
            return jsonify({
                'error': '请先登录',
                'message': '请先登录, 联系管理员'
            }), 400

        page = request.args.get('start', 0, type=int)
        per_page = request.args.get('size', 10, type=int)

        records_data = checker_task.get_user_record(user_id, page, per_page)
        return jsonify(records_data), 200

    @app.route('/records/tasks', methods=['GET'])
    def get_user_tasks():
        source = request.args.get('source')
        source_id = request.args.get('source_id')
        user_id = userservice.get_user_by_source_id(source_id, source)
        if user_id is None:
            return jsonify({
                'error': '请先登录',
                'message': '请先登录, 联系管理员'
            }), 400

        record_id = request.args.get('record_id', type=int)

        tasks_data = checker_task.get_record_task(record_id)
        return jsonify(tasks_data) 

    
    @app.route('/excel_upload', methods=['POST'])
    def excel_upload():
        source = request.args.get('source')
        source_id = request.args.get('source_id')
        user_id = userservice.get_user_by_source_id(source_id, source)
        if user_id is None:
            return jsonify({
                'error': '请先登录',
                'message': '请先登录, 联系管理员'
            }), 400

        if 'file' not in request.files:
            return jsonify({'error': '请上传Excel文件'}), 400
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': '未选择文件'}), 400
        try:
            # 保存临时文件
            original_name = request.form['original_name']
            if original_name == '':
                original_name = file.filename
            with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp:
                file.save(tmp.name)
                df = pd.read_excel(tmp.name)
            # 假设Excel有'product_name'和'pics'两列，pics为逗号分隔的图片路径或URL
            products = []
            for _, row in df.iterrows():
                pname = str(row.get('product_name', '')).strip()
                pics = str(row.get('product_pics', '')).split(',') if 'product_pics' in row and pd.notna(row['product_pics']) else []
                pics = [p.strip() for p in pics if p.strip()]
                products.append({'product_name': pname, 'product_pics': pics})
            record = checker_task.create_tasks_from_products(original_name, products, user_id, 1)
            return jsonify(record.task_to_dict()), 200
        except Exception as e:
            return jsonify({'error': 'Excel解析失败', 'message': str(e)}), 500 